var express = require('express');
var router = express.Router();
var StaticizeUtil = require('../../../common/util/StaticizeUtil');
var path=require('path');
var CONFIG = require('../../../common/config');
var CODE = require('../../../common/code');
var checkUtil = require('./../util/checkUtil');
var async  = require( 'async'); // 同步控制

var ItbBaseModel = require('./../../../common/mysql/mapping/ItbBaseModel');
var ItbActivityModel = require('./../../../common/mysql/mapping/ItbActivityModel');
var ItbActivityRModel = require('./../../../common/mysql/mapping/ItbActivityRModel');


//------------------------------------------------------------------
// 活动用
var redis = require("redis");
var redisClient = redis.createClient({
    host:CONFIG.ACTIVITY_REDIS_SERVER_DOMAIN,
    auth_pass:CONFIG.ACTIVITY_REDIS_SERVER_PASSWORD,
    port:CONFIG.ACTIVITY_REDIS_SERVER_PORT,
    db:CONFIG.ACTIVITY_REDIS_SERVER_DB_NUMBER,
    ttl:CONFIG.ACTIVITY_REDIS_SERVER_TTL,
});
var Scripto = require('redis-scripto');
var scriptManager = new Scripto(redisClient);
scriptManager.loadFromDir(__dirname+'/../../lua');


// 优惠券用
var redisClient2 = redis.createClient({
    host:CONFIG.COUPONS_REDIS_SERVER_DOMAIN,
    auth_pass:CONFIG.COUPONS_REDIS_SERVER_PASSWORD,
    port:CONFIG.COUPONS_REDIS_SERVER_PORT,
    db:CONFIG.COUPONS_REDIS_SERVER_DB_NUMBER,
    ttl:CONFIG.COUPONS_REDIS_SERVER_TTL,
});
var scriptManager2 = new Scripto(redisClient2);
scriptManager2.loadFromDir(__dirname+'/../../lua');


//------------------------------------------------------------------
var luaUtil = (function () {
    function luaUtil() {
    };

    //------------------------------------------------------------------
    // 返回json
    luaUtil.ret_func_json = function (success, msg, data, res){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    };

    //------------------------------------------------------------------
    // 测试用
    luaUtil.test = function(func, callback){
        if('lua_add_activity' == func){
            var keys    = [];
            var values  = [1, 'Logo秒杀专场','1498908628000', '1504265428000'];
            scriptManager.run(func, keys, values, function(err, result) {
                callback(err, result);
            });

        }else if('lua_add_activity_r' == func){
            var keys    = [];
            var values  = [1, 11, 3, 3];
            scriptManager.run(func, keys, values, function(err, result) {
                callback(err, result);
            });

        }else if('lua_del_activity' == func){
            var keys    = [];
            var values  = [1];
            scriptManager.run(func, keys, values, function(err, result) {
                callback(err, result);
            });

        }else if('lua_lock_activity_r' == func){
            var keys    = [];
            var values  = [11,222,1502294593162];
            scriptManager.run(func, keys, values, function(err, result) {
                callback(err, result);
            });

        }else if('lua_unlock_activity_r' == func){
            var keys    = [];
            var values  = [11,222];
            scriptManager.run(func, keys, values, function(err, result) {
                res.json(result);
            });
        }else if('lua_success_activity_r' == func){
            var keys    = [];
            var values  = [11,222];
            scriptManager.run(func, keys, values, function(err, result) {
                callback(err, result);
            });

        }else if('lua_expire_check' == func) {
            var keys = [];
            var values = [2502294593162, 5 * 60 * 1000];
            scriptManager.run(func, keys, values, function (err, result) {
                callback(err, result);
            });
        }else if('test_array_func_para' == func) {
            var keys    = [];
            var values  = [1, '11,12,13'];
            scriptManager.run(func, keys, values, function(err, result) {
                callback(err, result);
            });
        }else {
            callback('No func', null);
        }
    };

    //------------------------------------------------------------------
    /**
     * 锁定活动商品
     * @param rId 活动商品项目id
     * @param userId
     * @param callback
     */
    luaUtil.lockActivityItem = function(rId, userId, callback) {
        if(rId<=0 || userId<=0) {
            return callback('参数错误',null);
        }

        (new ItbBaseModel).getTimeFromDB(function(err, dbTimeInfo){
            if(dbTimeInfo) {

                var keys    = [];
                var values  = [rId, userId, (dbTimeInfo.ts_now||0)];
                scriptManager.run('lua_lock_activity_r', keys, values, function(err, result) {
                    //return: 0表示成功，1表示不存在场次或商品，2表示剩余锁不足，3表示用户抢购太频繁
                    if(result != 0) {
                        var e = '抢购失败,请稍后再试'; // **** 锁定失败
                        if(result==1) {
                            e='该场秒杀已结束'; // **** 不存在场次或商品
                        } else if(result==2) {
                            e='商品库存不足,请稍后再试'; // **** 余锁不足
                        } else if(result==3) {
                            e='抢购过于频繁,请稍后再试'; // **** 抢购太频繁
                        }
                        return callback(e, null);
                    }
                    return callback(err, result);
                });

            } else {
                return callback('获取时间戳失败', null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 更新锁记录为成功
     * @param rId 活动商品项目id
     * @param userId
     * @param callback
     */
    luaUtil.updLockActItemSuccess = function(rId, userId, callback) {
        if(rId<=0 || userId<=0) {
            return callback('参数错误',null);
        }

        var keys    = [];
        var values  = [rId, userId];
        scriptManager.run('lua_success_activity_r', keys, values, function(err, result) {
            //return: 0表示成功，1表示不存在场次或商品，2表示用户未加锁
            return callback(err, result);
        });
    };

    //------------------------------------------------------------------
    /**
     * 解锁活动商品
     * @param rId 活动商品项目id
     * @param userId
     * @param callback
     */
    luaUtil.unlockActivityItem = function(rId, userId, callback) {
        if(rId<=0 || userId<=0) {
            return callback('参数错误',null);
        }

        var keys    = [];
        var values  = [rId, userId];
        scriptManager.run('lua_unlock_activity_r', keys, values, function(err, result) {
            //return: 0表示成功，1表示不存在场次或商品，2表示用户未加锁
            if(err) {
                console.log("luaUitl.js [unlockActivityItem] unlock Err: " + err);
            }
            return callback(null, result);// TODO
        });
    };

    //------------------------------------------------------------------
    /**
     * 删除活动场次
     * @param actId
     * @param callback
     */
    luaUtil.delActivity = function(actId, callback) {
        actId = Number(actId||'0')||0;
        if(actId<=0) {
            return callback('参数错误',null);
        }

        var keys    = [];
        var values  = [actId];
        scriptManager.run('lua_del_activity', keys, values, function(err, result) {
            return callback(err, result);
        });
    };

    //------------------------------------------------------------------
    /**
     * 添加活动场次及活动商品
     * @param actId
     * @param callback
     */
    luaUtil.addActivityAndItems = function(actId, callback) {
        actId = Number(actId||'0')||0;
        if(actId<=0) {
            return callback('参数错误',null);
        }

        // 检索活动场次
        (new ItbActivityModel).getActInfoById(actId, function(findErr, actInfo){
            if(findErr) {
                console.log("luaUitl.js [addActivityAndItems] getActInfoById Err: " + findErr);
                return callback(findErr, null);
            }

            if(actInfo) {
                var asyncFuncs = [];

                // 插入活动场次信息
                asyncFuncs.push(function(asyncCallback){
                    var values  = [
                        actInfo.act_id,
                        actInfo.title||'',
                        actInfo.ts_start_time||0,
                        actInfo.ts_end_time||0
                    ];
                    scriptManager.run('lua_add_activity', [], values, function(err, result) {
                        return asyncCallback(err, result);
                    });
                });

                // 检索活动商品
                (new ItbActivityRModel).getActItemInfoByActId(actId, function(findErr2, actItemLst){
                    if(findErr2) {
                        console.log("luaUitl.js [addActivityAndItems] getActItemInfoByActId Err: " + findErr2);
                        return callback(findErr2, null);
                    }

                    if(actItemLst && actItemLst.length>0) {
                        // 插入活动商品信息
                        for(var i=0; i<actItemLst.length; i++) {
                            asyncFuncs.push((function (idx, actItemInfo) {
                                return function (asyncCallback) {
                                    var values  = [
                                        actItemInfo.act_id,
                                        actItemInfo.r_id,
                                        actItemInfo.qty||0,
                                        actItemInfo.rest_qty||0
                                    ];
                                    scriptManager.run('lua_add_activity_r', [], values, function(err, result) {
                                        return asyncCallback(err, result);
                                    });
                                }
                            })(i, actItemLst[i])); // 利用闭包解决动态参数传递问题
                        }

                        // 批量处理
                        async.series(asyncFuncs,
                            function(error, results) {
                                if (error) {
                                    console.log("luaUitl.js [addActivityAndItems] async Err: " + error);
                                    return callback(error, null);
                                }

                                return callback(null, results);
                            }
                        );

                    } else {
                        console.log("luaUitl.js [addActivityAndItems] No ActItemsInfo");
                        return callback('未检索到活动商品信息',null);
                    }
                });


            } else {
                console.log("luaUitl.js [addActivityAndItems] No ActInfo");
                return callback('未检索到活动信息',null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 自动解锁超时商品项目
     * 参数 expLim: 超时时长,单位秒,默认300秒
     */
    luaUtil.unlockExpireItem = function(expLim, callback) {
        expLim = Number(expLim||'0')||0;

        (new ItbBaseModel).getTimeFromDB(function(err, dbTimeInfo){
            if(dbTimeInfo) {

                var keys    = [];
                var values  = [(dbTimeInfo.ts_now||0), expLim];
                scriptManager.run('lua_expire_check', keys, values, function(err, result) {
                    return callback(err, result);
                });

            } else {
                return callback('获取时间戳失败', null);
            }
        });
    };


    //------------------------------------------------------------------
    /**
     * 抽取指定优惠券
     * 参数 use: 用途
     */
    luaUtil.getCouponRandom = function(use, callback) {

        if(use>0) {
            var keys    = [];
            var values  = [use];
            scriptManager2.run('lua_get_coupon_random', keys, values, function(err, result) {
                return callback(err, result);
            });
        } else {
            return callback(null,'');
        }
    };

    luaUtil.setCoupon = function(use,value,callback) {

        if(use>0 && value && value.length>0) {
            var keys    = [];
            var values  = [use, value];
            scriptManager2.run('lua_set_coupon', keys, values, function(err, result) {
                return callback(err, result);
            });
        } else {
            return callback('NG','');
        }
    };
    luaUtil.resetCoupon = function(use,callback) {

        if(use>0) {
            var keys    = [];
            var values  = [use];
            scriptManager2.run('lua_reset_coupon', keys, values, function(err, result) {
                return callback(err, result);
            });
        } else {
            return callback('NG','');
        }
    };

    //------------------------------------------------------------------
    return luaUtil;
})();

//------------------------------------------------------------------
module.exports = luaUtil;

